﻿using System;
using System.Collections.Generic;
using System.Linq;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Media;

namespace App29
{
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
        }

        public double ItemHeight
        {
            get { return Window.Current.Bounds.Height; }
        }

        private void MyGridView_Loaded(object sender, RoutedEventArgs args)
        {
            float itemWidth = 800;

            this.ScrollViewer.HorizontalSnapPointsType = SnapPointsType.MandatorySingle;
            this.ScrollViewer.HorizontalSnapPointsAlignment = SnapPointsAlignment.Center;

            GoLeftMarker.PointerPressed += (s, e) =>
                this.ScrollViewer.ChangeView(this.ScrollViewer.HorizontalOffset - itemWidth, null, null);
            GoRightMarker.PointerPressed += (s, e) =>
                this.ScrollViewer.ChangeView(this.ScrollViewer.HorizontalOffset + itemWidth, null, null);

            this.ScrollViewer.ViewChanged += (s, e) =>
            {
                if (e.IsIntermediate)
                    return;

                // hide/show left
                if (this.ScrollViewer.HorizontalOffset < (itemWidth + itemWidth * .25))
                    this.GoLeftMarker.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                else
                    this.GoLeftMarker.Visibility = Windows.UI.Xaml.Visibility.Visible;

                // hide/show right
                if (this.ScrollViewer.HorizontalOffset > this.ScrollViewer.ScrollableWidth - (itemWidth + itemWidth * .25))
                    this.GoRightMarker.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                else
                    this.GoRightMarker.Visibility = Windows.UI.Xaml.Visibility.Visible;
            };
            this.ScrollViewer.ChangeView(itemWidth * .5, null, null);
        }

        ScrollViewer scrollViewer = default(ScrollViewer);
        ScrollViewer ScrollViewer
        {
            get
            {
                if (scrollViewer != null)
                    return scrollViewer;
                var children = RecurseChildren(this.MyGridView);
                return scrollViewer = children.First(x => x.Name.Equals("ScrollViewer")) as ScrollViewer;
            }
        }

        public List<Control> RecurseChildren(DependencyObject parent)
        {
            var _List = new List<Control>();
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
            {
                var _Child = VisualTreeHelper.GetChild(parent, i);
                if (_Child is Control)
                    _List.Add(_Child as Control);
                _List.AddRange(RecurseChildren(_Child));
            }
            return _List;
        }
    }
}
